package com.cloudbroker.openapi.manage.websocket;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Logger;

import javax.websocket.CloseReason;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import org.eclipse.jetty.websocket.api.annotations.OnWebSocketMessage;
import org.eclipse.jetty.websocket.api.annotations.WebSocket;

//注意此访问地址格式如:"ws://"+ window.location.host+"/${pageContext.request.contextPath}/game"是ws开头的,而不是以http:开头的.
@ServerEndpoint(value = "/game")
@WebSocket(maxTextMessageSize = 64 * 1024)
public class NoticeScoket {
	private Logger logger = Logger.getLogger(this.getClass().getName());

	private static NoticeScoket instance = new NoticeScoket();

	private NoticeScoket() {

	}

	public static NoticeScoket getInstance() {
		return instance;
	}

	static Map<String, Session> sessionMap = new ConcurrentHashMap<String, Session>();

	@OnOpen
	public void onOpen(Session session) {
		sessionMap.put(session.getId(), session);
	}

	@OnMessage
	@OnWebSocketMessage
	public void onMessage(String unscrambledWord, Session session) {
		broadcastAll("message", unscrambledWord);
	}

	/**
	 * 广播给所有人
	 * 
	 * @param message
	 */
	private static void broadcastAll(String type, String message) {
		Set<Map.Entry<String, Session>> set = sessionMap.entrySet();
		for (Map.Entry<String, Session> i : set) {
			try {
				i.getValue()
						.getBasicRemote()
						.sendText(
								"{type:'" + type + "',text:'" + message + "'}");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	@OnClose
	public void onClose(Session session, CloseReason closeReason) {
		sessionMap.remove(session.getId());
		logger.info(String.format("Session %s closed because of %s",
				session.getId(), closeReason));
	}

	@OnError
	public void error(Session session, java.lang.Throwable throwable) {
		sessionMap.remove(session.getId());
		System.err
				.println("session " + session.getId() + " error:" + throwable);
	}
}
